import { PaperType } from "@/types";
import { ProTable } from "@ant-design/pro-components";
import type { ActionType, ProColumns } from "@ant-design/pro-components";
import { Modal, Select } from "antd";
import { useEffect, useRef, useState } from "react";
import request from "@/services/interceptors";

interface PaperSelectProps {
  value?: number[];
  onChange?: (value: number[]) => void;
  multiple?: boolean;
  initData?: PaperType[];
}

const PaperSelect: React.FC<PaperSelectProps> = ({
  value = [],
  onChange,
  multiple = true,
  initData = [],
}) => {
  const [open, setOpen] = useState(false);
  const [selectedRows, setSelectedRows] = useState<PaperType[]>([]);
  const [selectedKeys, setSelectedKeys] = useState<number[]>(value || []);
  const actionRef = useRef<ActionType>(null);
  // 初始化已选数据
  // 初始化已选数据
  useEffect(() => {
    if (initData.length) {
      setSelectedRows(initData);
      setSelectedKeys(initData.map((item) => +item.paperId));
    }
  }, [initData]);
  // 处理选择变化
  const handleSelectionChange = (keys: any[], rows: PaperType[]) => {
    setSelectedKeys(keys);
    setSelectedRows(rows);
  };

  const columns: ProColumns<PaperType>[] = [
    {
      title: "试卷ID",
      dataIndex: "paperId",
      hideInSearch: true,
      hideInTable: true,
    },
    {
      title: "试卷名称",
      dataIndex: "name",
    },
    {
      title: "客观题数量",
      dataIndex: "questionCount",
      hideInSearch: true,
    },
    {
      title: "操作题数量",
      dataIndex: "exerciseCount",
      hideInSearch: true,
    },
    {
      title: "总分",
      dataIndex: "score",
      hideInSearch: true,
    },
    {
      title: "创建时间",
      dataIndex: "createTime",
      hideInSearch: true,
    },
    {
      title: "更新时间",
      dataIndex: "updateTime",
      hideInSearch: true,
    },
  ];

  return (
    <>
      <Select
        placeholder="请选择试卷"
        mode={multiple ? "multiple" : undefined}
        value={value}
        onChange={onChange}
        onClick={() => setOpen(true)}
        style={{ width: "100%" }}
        options={selectedRows.map((item) => ({
          label: `${item.name}`,
          value: item.paperId,
        }))}
      />
      <Modal
        title="选择试卷"
        open={open}
        onOk={() => {
          onChange?.(selectedKeys);
          setOpen(false);
        }}
        onCancel={() => setOpen(false)}
        width={800}
      >
        <ProTable<PaperType>
          columns={columns}
          actionRef={actionRef}
          cardBordered
          options={false}
          rowKey="paperId"
          rowSelection={{
            type: multiple ? "checkbox" : "radio",
            selectedRowKeys: selectedKeys,
            onChange: handleSelectionChange,
            preserveSelectedRowKeys: true, // 保持选中状态
          }}
          tableAlertRender={false}
          pagination={{ pageSize: 10 }}
          request={async (params) => {
            const res = await request.sgks.paperListList({
              ...params,
              pageNo: params.current,
              pageSize: params.pageSize,
            });
            return {
              data: res.data.records,
              total: res.data.totalCount,
            };
          }}
        />
      </Modal>
    </>
  );
};

export default PaperSelect;
